package cvut.cz.via.android;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainMenuActivity extends ListActivity {
	
	static final String[] ITEMS = new String[] {"My courses", "Subscribe to Courses", "Settings"};
	private StudyMaterialsApplication sma;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu_activity);
		setListAdapter(new ArrayAdapter<String>(this, R.layout.main_menu_item, ITEMS));
		sma = (StudyMaterialsApplication)getStudyMaterialsApplication();
		Log.d("USER", sma.user.toString());
		finishActivity(1);
		Log.d("USER", sma.user.toString());
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		//super.onListItemClick(l, v, position, id);
		Intent intent = new Intent();
		switch(position) {
			case 0 : {
				intent = new Intent(MainMenuActivity.this, MyCoursesActivity.class);
				break;
			}
			case 1 : {
				intent = new Intent(MainMenuActivity.this, SubscribeCoursesActivity.class);
				break;
			}
			case 2 : {
				intent = new Intent(MainMenuActivity.this, SettingsActivity.class);
				break;
			}
			default : {
				break;
			}
		}		
		startActivity(intent);		
	}
	
	private StudyMaterialsApplication getStudyMaterialsApplication() {
		StudyMaterialsApplication sma = (StudyMaterialsApplication)getApplication();
		return sma;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
		ObjectOutput out;
		try {
			out = new ObjectOutputStream(bos);		
			out.writeObject(sma.user);
			byte[] buf = bos.toByteArray();
	        FileOutputStream fos = this.openFileOutput("config.dat", Context.MODE_PRIVATE);
	        fos.write(buf);
	        fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Log.d("USER_SAVED", sma.user.toString());
	}
	
	
	
	
	
}
